/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.isfd.service.impl;

import java.io.IOException;
import java.util.*;

import com.alibaba.excel.EasyExcel;
import com.comac.ins.common.core.utils.file.FileUtils;
import com.comac.ins.common.json.utils.JsonUtils;
import com.comac.ins.isfd.domain.IsfdAnalysisParameterConfig;
import com.comac.ins.isfd.domain.bo.IsfdDatasourceTemplateConditionBo;
import com.comac.ins.isfd.domain.bo.IsfdDatasourceTemplateQueryBo;
import com.comac.ins.isfd.domain.bo.TempalteExcelBo;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.comac.ins.common.core.domain.model.LoginUser;
import com.comac.ins.common.core.utils.MapstructUtils;
import com.comac.ins.common.core.utils.StringUtils;
import com.comac.ins.common.mybatis.core.page.PageQuery;
import com.comac.ins.common.mybatis.core.page.TableDataInfo;
import com.comac.ins.common.satoken.utils.LoginHelper;
import com.comac.ins.isfd.domain.IsfdDatasourceTemplate;
import com.comac.ins.isfd.domain.bo.IsfdDatasourceTemplateBo;
import com.comac.ins.isfd.domain.vo.IsfdDatasourceTemplateVo;
import com.comac.ins.isfd.mapper.IsfdDatasourceTemplateMapper;
import com.comac.ins.isfd.service.IIsfdDatasourceTemplateService;
import lombok.RequiredArgsConstructor;

/**
 * 数据源数据模版Service业务层处理
 *
 * @author Lion Li
 * @date 2024-10-11
 */
@RequiredArgsConstructor
@Service
public class IsfdDatasourceTemplateServiceImpl implements IIsfdDatasourceTemplateService {

   @Autowired
    private  IsfdDatasourceTemplateMapper baseMapper;
    @Autowired
    private  IsfdDatasourceTemplateMapper isfdDatasourceTemplateMapper;

    /**
     * 查询数据源数据模版
     *
     * @param id 主键
     * @return 数据源数据模版
     */
    @Override
    public IsfdDatasourceTemplateVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询数据源数据模版列表
     *
     * @param bo        查询条件
     * @return 数据源数据模版分页列表
     */
    @Override
    public TableDataInfo<IsfdDatasourceTemplateVo> queryPageList(IsfdDatasourceTemplateQueryBo bo) {
        LambdaQueryWrapper<IsfdDatasourceTemplate> lqw = buildQueryWrapper(bo);
        PageQuery pageQuery = new PageQuery();
        pageQuery.setPageNum(bo.getPageNum());
        pageQuery.setPageSize(bo.getPageSize());
        pageQuery.setOrderByColumn("create_time");
        pageQuery.setIsAsc(bo.getIsAsc());
        Page<IsfdDatasourceTemplateVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        // 处理模板状态
        for(IsfdDatasourceTemplateVo template: result.getRecords()){
            // 查询模板是否使用
            Integer hasUsed = isfdDatasourceTemplateMapper.queryTemplateHasUsed(template.getId());
            template.setStatus(hasUsed>0?1:0);
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的数据源数据模版列表
     *
     * @param bo 查询条件
     * @return 数据源数据模版列表
     */
    @Override
    public List<IsfdDatasourceTemplateVo> queryList(IsfdDatasourceTemplateQueryBo bo) {
        LambdaQueryWrapper<IsfdDatasourceTemplate> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<IsfdDatasourceTemplate> buildQueryWrapper(IsfdDatasourceTemplateQueryBo bo) {
        LambdaQueryWrapper<IsfdDatasourceTemplate> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getTemplateName()), IsfdDatasourceTemplate::getTemplateName, bo.getTemplateName());
        lqw.eq(bo.getBusinessId() != null, IsfdDatasourceTemplate::getBusinessId, bo.getBusinessId());
        return lqw;
    }

    /**
     * 新增数据源数据模版
     *
     * @param bo 数据源数据模版
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(IsfdDatasourceTemplateBo bo) {
        IsfdDatasourceTemplate add = MapstructUtils.convert(bo, IsfdDatasourceTemplate.class);
        validEntityBeforeSave(add);
        LoginUser loginUser = LoginHelper.getLoginUser();
        bo.setCreateBy(loginUser.getUserId());
        bo.setUpdateBy(loginUser.getUserId());
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改数据源数据模版
     *
     * @param bo 数据源数据模版
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(IsfdDatasourceTemplateBo bo) {
        IsfdDatasourceTemplate update = MapstructUtils.convert(bo, IsfdDatasourceTemplate.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(IsfdDatasourceTemplate entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除数据源数据模版信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public void exportExcelById(IsfdDatasourceTemplateQueryBo bo, HttpServletResponse response) {
        // 查詢模板字段
        IsfdDatasourceTemplateVo isfdDatasourceTemplateVo = baseMapper.selectVoById(bo.getTemplateId());
        String params = isfdDatasourceTemplateVo.getMapFields();
        List<TempalteExcelBo> paramsList = JsonUtils.parseArray(params, TempalteExcelBo.class);
        List<List<String>> heads = new ArrayList<>();
        List<String> cells = new ArrayList<>(); //表头信息
        for(TempalteExcelBo item:paramsList){
            cells.add(item.getTargetField());
        }
        heads.add(cells);
        try {
        List resultList = new ArrayList<>();
        resultList.addAll(0,heads);
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            ServletOutputStream os = response.getOutputStream();
            EasyExcel.write(os).sheet("模板").doWrite(resultList);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

    @Override
    public TableDataInfo<IsfdDatasourceTemplateVo> queryTemplateByCondition(IsfdDatasourceTemplateConditionBo isfdDatasourceTemplateConditionBo) {
        List<IsfdDatasourceTemplateVo> resultList = isfdDatasourceTemplateMapper.queryTemplateByCondition(isfdDatasourceTemplateConditionBo.getBusinessId(),isfdDatasourceTemplateConditionBo.getDatabaseType());
        return TableDataInfo.build(resultList);
    }
}
